<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket测试页面</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        
        h1 {
            text-align: center;
            margin-bottom: 30px;
            color: #2c3e50;
        }
        
        .connection-panel {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        
        .connection-info {
            margin-bottom: 15px;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        
        input[type="text"],
        input[type="number"],
        textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        
        textarea {
            height: 150px;
            resize: vertical;
        }
        
        .btn-group {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        
        button {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            font-size: 14px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        
        .btn-connect {
            background-color: #28a745;
            color: white;
        }
        
        .btn-connect:hover {
            background-color: #218838;
        }
        
        .btn-disconnect {
            background-color: #dc3545;
            color: white;
        }
        
        .btn-disconnect:hover {
            background-color: #c82333;
        }
        
        .btn-send {
            background-color: #007bff;
            color: white;
        }
        
        .btn-send:hover {
            background-color: #0056b3;
        }
        
        .message-panel {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        
        .message-list {
            background-color: white;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 10px;
            height: 300px;
            overflow-y: auto;
            margin-bottom: 15px;
        }
        
        .message {
            margin-bottom: 10px;
            padding: 8px;
            border-radius: 4px;
            background-color: #e9ecef;
        }
        
        .message.system {
            background-color: #d1ecf1;
            color: #0c5460;
        }
        
        .message.from-me {
            background-color: #d4edda;
            color: #155724;
            text-align: right;
        }
        
        .message.from-other {
            background-color: #f8d7da;
            color: #721c24;
        }
        
        .message-time {
            font-size: 12px;
            color: #666;
            margin-bottom: 4px;
        }
        
        .message-content {
            word-wrap: break-word;
        }
        
        .status {
            padding: 10px;
            border-radius: 4px;
            margin-bottom: 15px;
            font-weight: bold;
        }
        
        .status.connected {
            background-color: #d4edda;
            color: #155724;
        }
        
        .status.disconnected {
            background-color: #f8d7da;
            color: #721c24;
        }
        
        .clients-panel {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
        }
        
        .clients-list {
            background-color: white;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 10px;
            min-height: 100px;
            max-height: 200px;
            overflow-y: auto;
        }
        
        .client-item {
            padding: 5px;
            border-bottom: 1px solid #eee;
        }
        
        .client-item:last-child {
            border-bottom: none;
        }
        
        .client-item.me {
            font-weight: bold;
            color: #007bff;
        }
    </style>
</head>
<body>
    <h1>WebSocket测试页面</h1>
    
    <div class="connection-panel">
        <div class="form-group">
            <label for="server-url">WebSocket服务器地址</label>
            <input type="text" id="server-url" value="ws://127.0.0.1:8282" placeholder="ws://localhost:8282">
        </div>
        
        <div class="btn-group">
            <button id="connect-btn" class="btn-connect">连接</button>
            <button id="disconnect-btn" class="btn-disconnect" disabled>断开连接</button>
        </div>
        
        <div id="connection-status" class="status disconnected">
            未连接
        </div>
        
        <div id="connection-info" class="connection-info">
            <p>连接信息: 等待连接...</p>
        </div>
    </div>
    
    <div class="message-panel">
        <div class="form-group">
            <label for="message-type">消息类型</label>
            <select id="message-type">
                <option value="broadcast">广播消息(发送给所有人)</option>
                <option value="private">私聊消息(发送给指定客户端)</option>
            </select>
        </div>
        
        <div class="form-group" id="target-client-group" style="display: none;">
            <label for="target-client">目标客户端ID</label>
            <input type="text" id="target-client" placeholder="输入目标客户端ID">
        </div>
        
        <div class="form-group">
            <label for="message-input">消息内容</label>
            <textarea id="message-input" placeholder="输入要发送的消息..."></textarea>
        </div>
        
        <button id="send-btn" class="btn-send" disabled>发送消息</button>
        
        <div class="message-list" id="message-list">
            <!-- 消息列表将在这里显示 -->
        </div>
    </div>
    
    <div class="clients-panel">
        <h3>在线客户端</h3>
        <div class="clients-list" id="clients-list">
            <!-- 客户端列表将在这里显示 -->
        </div>
    </div>
    
    <script>
        // WebSocket连接对象
        let ws = null;
        // 当前客户端ID
        let clientId = null;
        // 客户端列表
        let clients = [];
        
        // DOM元素
        const serverUrlInput = document.getElementById('server-url');
        const connectBtn = document.getElementById('connect-btn');
        const disconnectBtn = document.getElementById('disconnect-btn');
        const connectionStatus = document.getElementById('connection-status');
        const connectionInfo = document.getElementById('connection-info');
        const messageTypeSelect = document.getElementById('message-type');
        const targetClientGroup = document.getElementById('target-client-group');
        const targetClientInput = document.getElementById('target-client');
        const messageInput = document.getElementById('message-input');
        const sendBtn = document.getElementById('send-btn');
        const messageList = document.getElementById('message-list');
        const clientsList = document.getElementById('clients-list');
        
        // 连接按钮点击事件
        connectBtn.addEventListener('click', connect);
        // 断开连接按钮点击事件
        disconnectBtn.addEventListener('click', disconnect);
        // 发送消息按钮点击事件
        sendBtn.addEventListener('click', sendMessage);
        // 消息类型选择事件
        messageTypeSelect.addEventListener('change', toggleTargetClient);
        // 回车键发送消息
        messageInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });
        
        // 初始化
        function init() {
            toggleTargetClient();
        }
        
        // 切换目标客户端输入框显示
        function toggleTargetClient() {
            if (messageTypeSelect.value === 'private') {
                targetClientGroup.style.display = 'block';
            } else {
                targetClientGroup.style.display = 'none';
            }
        }
        
        // 连接WebSocket服务器
        function connect() {
            const serverUrl = serverUrlInput.value;
            
            if (!serverUrl) {
                alert('请输入WebSocket服务器地址');
                return;
            }
            
            try {
                // 创建WebSocket连接
                ws = new WebSocket(serverUrl);
                
                // 连接成功事件
                ws.onopen = function(event) {
                    connectionStatus.textContent = '已连接';
                    connectionStatus.className = 'status connected';
                    connectBtn.disabled = true;
                    disconnectBtn.disabled = false;
                    sendBtn.disabled = false;
                    addMessage('system', '系统', '已成功连接到WebSocket服务器');
                };
                
                // 接收消息事件
                ws.onmessage = function(event) {
                    try {
                        const data = JSON.parse(event.data);
                        handleMessage(data);
                    } catch (e) {
                        addMessage('system', '系统', '收到无法解析的消息: ' + event.data);
                    }
                };
                
                // 连接关闭事件
                ws.onclose = function(event) {
                    connectionStatus.textContent = '未连接';
                    connectionStatus.className = 'status disconnected';
                    connectBtn.disabled = false;
                    disconnectBtn.disabled = true;
                    sendBtn.disabled = true;
                    clientId = null;
                    clients = [];
                    updateClientsList();
                    addMessage('system', '系统', 'WebSocket连接已关闭');
                    connectionInfo.innerHTML = '<p>连接信息: 等待连接...</p>';
                };
                
                // 连接错误事件
                ws.onerror = function(event) {
                    addMessage('system', '系统', 'WebSocket连接错误');
                };
            } catch (e) {
                alert('连接失败: ' + e.message);
            }
        }
        
        // 断开WebSocket连接
        function disconnect() {
            if (ws) {
                ws.close();
                ws = null;
            }
        }
        
        // 发送消息
        function sendMessage() {
            if (!ws || ws.readyState !== WebSocket.OPEN) {
                alert('WebSocket未连接');
                return;
            }
            
            const message = messageInput.value.trim();
            if (!message) {
                alert('请输入消息内容');
                return;
            }
            
            const messageType = messageTypeSelect.value;
            let data = { type: messageType, message: message };
            
            // 如果是私聊消息，添加目标客户端ID
            if (messageType === 'private') {
                const targetClient = targetClientInput.value.trim();
                if (!targetClient) {
                    alert('请输入目标客户端ID');
                    return;
                }
                data.to = targetClient;
            }
            console.log(data);
            // 发送消息
            ws.send(JSON.stringify(data));
            
            // 清空输入框
            messageInput.value = '';
        }
        
        // 处理接收到的消息
        function handleMessage(data) {
            switch (data.type) {
                case 'connect':
                    // 连接成功消息
                    clientId = data.client_id;
                    connectionInfo.innerHTML = `<p>连接信息: 客户端ID = ${clientId}</p>`;
                    break;
                    
                case 'system':
                    // 系统消息
                    addMessage('system', '系统', data.message + (data.client_id ? ` (客户端ID: ${data.client_id})` : ''));
                    if (data.total_clients !== undefined) {
                        addMessage('system', '系统', `当前在线客户端数: ${data.total_clients}`);
                    }
                    break;
                    
                case 'message':
                    // 广播消息
                    if (data.from === clientId) {
                        addMessage('from-me', '我', data.message);
                    } else {
                        addMessage('from-other', `客户端 ${data.from}`, data.message);
                    }
                    break;
                    
                case 'private':
                    // 私聊消息
                    if (data.to === clientId || data.from === clientId) {
                        if (data.from === clientId) {
                            addMessage('from-me', `我 -> 客户端 ${data.to}`, data.message);
                        } else {
                            addMessage('from-other', `客户端 ${data.from} -> 我`, data.message);
                        }
                    }
                    break;
                    
                case 'error':
                    // 错误消息
                    addMessage('system', '错误', data.message);
                    break;
                    
                case 'pong':
                    // 心跳响应
                    console.log('收到心跳响应');
                    break;
                    
                default:
                    // 其他消息
                    addMessage('system', '系统', '收到未知类型消息: ' + JSON.stringify(data));
                    break;
            }
        }
        
        // 添加消息到消息列表
        function addMessage(type, sender, content) {
            const messageTime = new Date().toLocaleString();
            const messageElement = document.createElement('div');
            messageElement.className = `message ${type}`;
            messageElement.innerHTML = `
                <div class="message-time">${messageTime} - ${sender}</div>
                <div class="message-content">${content}</div>
            `;
            messageList.appendChild(messageElement);
            
            // 滚动到底部
            messageList.scrollTop = messageList.scrollHeight;
        }
        
        // 更新客户端列表
        function updateClientsList() {
            clientsList.innerHTML = '';
            
            if (clients.length === 0) {
                clientsList.innerHTML = '<div class="client-item">暂无在线客户端</div>';
                return;
            }
            
            clients.forEach(id => {
                const clientElement = document.createElement('div');
                clientElement.className = `client-item ${id === clientId ? 'me' : ''}`;
                clientElement.textContent = id + (id === clientId ? ' (我)' : '');
                
                // 点击客户端ID自动填充到目标客户端输入框
                if (id !== clientId) {
                    clientElement.style.cursor = 'pointer';
                    clientElement.addEventListener('click', function() {
                        targetClientInput.value = id;
                    });
                }
                
                clientsList.appendChild(clientElement);
            });
        }
        
        // 定期发送心跳消息保持连接
        setInterval(() => {
            if (ws && ws.readyState === WebSocket.OPEN) {
                ws.send(JSON.stringify({ type: 'ping' }));
            }
        }, 30000);
        
        // 页面加载完成后初始化
        window.addEventListener('load', init);
    </script>
</body>
</html>